package cn.miju.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <pre>
 * 驼峰转换工具类
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-22 14:18
 */
public class CamelCaseUtil {
    private static final  Pattern TO_CAMEL_COMPILE = Pattern.compile("_[a-z]");
    private static final  Pattern TO_SNAKE_COMPILE = Pattern.compile("[A-Z]");

    /**
     * 下划线转驼峰
     * @param str 下划线字符串
     * @return 驼峰字符串
     */
    public static String snakeToCamel(String str) {
        Matcher matcher = TO_CAMEL_COMPILE.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb,  matcher.group(0).toUpperCase().replace("_",""));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    /**
     * 驼峰转下划线
     * @param str 下划线字符串
     * @return 驼峰字符串
     */
    public static String camelToSnake(String str) {
        Matcher matcher = TO_SNAKE_COMPILE.matcher(str.toLowerCase());
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb,  "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
